#include <stdio.h>
#include <stdlib.h>
#include "stdint.h"

int main(int argc, char *argv[]) {

    if (argc < 3) {
        fprintf(stderr, "用法: %s <输入BMP文件> <输出BIN文件>\n", argv[0]);
        return 1;
    }

    const char* inputFile = argv[1];
    const char* outputFile = argv[2] ? argv[2] : "output.bin";
    
    // 打开WAV文件
    FILE *bmpFile = fopen(inputFile, "rb");
    if (!bmpFile) {
        perror("❌ 无法打开输入文件");
        return 1;
    }

    // 获取文件大小
    fseek(bmpFile, 0, SEEK_END);
    long fileSize = ftell(bmpFile);
    fseek(bmpFile, 0, SEEK_SET);

    uint8_t data[70];
    uint8_t bmpHeaderOffset = 0;
    if ((fread(data, 1, 70, bmpFile))) {
        bmpHeaderOffset = data[11] << 8 | data[10];
        printf("bmpHeaderOffset:%d\n", bmpHeaderOffset);
    }

    uint32_t dataSize = fileSize - bmpHeaderOffset;
    uint32_t writeDataSize = dataSize - 2;
   
    // 定位并读取WAV数据
    fseek(bmpFile, bmpHeaderOffset, SEEK_SET);
    unsigned char *bmpData = malloc(writeDataSize);
    if (!bmpData) {
        printf("⚠️ 内存分配失败\n");
        fclose(bmpFile);
        return 1;
    }

    if (fread(bmpData, 1, dataSize, bmpFile) != dataSize) {
        printf("⚠️ 像素数据读取失败\n");
        free(bmpData);
        fclose(bmpFile);
        return 1;
    }
    fclose(bmpFile);

    // 交换相邻字节的高低位
    for (long i = 0; i < dataSize - 1; i += 2) {
        unsigned char temp = bmpData[i];
        bmpData[i] = bmpData[i + 1];
        bmpData[i + 1] = temp;
    }

    // 打开BIN文件
    FILE *binFile = fopen(outputFile, "wb");
    if (!binFile) {
        perror("Error creating BIN file");
        free(bmpData);
        return EXIT_FAILURE;
    }

    // 写入BIN文件
    size_t writeLen = fwrite(bmpData, 1, writeDataSize, binFile);
    if (writeLen != writeDataSize) {
        perror("Error writing to BIN file");
    }

    free(bmpData);
    fclose(binFile);

    printf("Conversion successful!\n");
    printf("Removed %d bytes header\n", bmpHeaderOffset + 2);
    printf("Output file: %s (%ld bytes)\n", outputFile, writeLen);

    return 0;
}